<template>
  <div>
    <el-input v-model="msg" placeholder="请输入内容" clearable></el-input>
    <el-button type="primary" @click="send">发送</el-button>
    <el-button type="success" @click="init">连接</el-button>

    <div id="output">{{sendMessage}}</div>
  </div>
</template>

<script>
  export default {
    name: "chatn",
    data() {
      return {
        sendMessage: [],
        msg: '',
        websocket: '',

      };
    },
    created() {
      this.init();
    },
    methods: {
      init() {
        const wsuri = 'ws://localhost:2019/ws';
        // const wsuri = 'ws://localhost:2020/stu/chat/chat';
        this.websocket = new WebSocket(wsuri);
        this.websocket.onopen = this.onOpen;
        this.websocket.onmessage = this.websocketonmessage;
        console.log(this.websocket.readyState);
      },

      // 连接成功
      onOpen() {
        this.sendMessage = [];
        // 在div打印连接成功
        this.sendMessage.push("连接成功")
      },

      // 发送数据
      send() {
        this.sendMessage.push("发送消息:" + this.msg);
        if (this.websocket.readyState === 1) {
          this.websocket.send(this.msg);
        } else {
          console.log("发送失败哦");
        }

      },

      // 接收数据
      websocketonmessage(e) {
        let str = "接受到消息：" + e.data;
        this.sendMessage.push(str);
      },

    }
  };
</script>
